package com.hsogoo.ultraman.spi;

import java.util.Map;

import com.google.common.collect.Maps;
import com.hsogoo.ultraman.Config;
import com.hsogoo.ultraman.ConfigFactory;
import com.hsogoo.ultraman.container.ConfigContainer;
import com.hsogoo.ultraman.enums.ConfigFileType;
import com.hsogoo.ultraman.repository.ConfigRepository;
import com.hsogoo.ultraman.repository.LocalFileConfigRepository;
import com.hsogoo.ultraman.repository.RemoteConfigRepository;
import com.hsogoo.ultraman.utils.ConfigMetaUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * Created by za-huangsaigang on 2018/9/13.
 */
@Slf4j
public class DefaultConfigFactory implements ConfigFactory {

    private Map<String, Config> configs = Maps.newConcurrentMap();

    @Override
    public Config getConfig(String namespace) {
        Config config = configs.get(namespace);

        if (config == null) {
            synchronized (this) {
                config = configs.get(namespace);
                if (config == null) {
                    config = new DefaultConfig(namespace, createLocalConfigRepository(namespace));
                    configs.put(namespace, config);
                }
            }
        }
        return config;
    }

    private LocalFileConfigRepository createLocalConfigRepository(String namespace) {
        ConfigMetaUtil configMetaUtil = ConfigContainer.getBean(ConfigMetaUtil.class);
        if (configMetaUtil.isLocalMode()) {
            log.info("==== config is in local mode! use local config file for namespace {} ! ====", namespace);
            return new LocalFileConfigRepository(namespace);
        }
        return new LocalFileConfigRepository(namespace, createRemoteConfigRepository(namespace));
    }

    private RemoteConfigRepository createRemoteConfigRepository(String namespace) {
        return new RemoteConfigRepository(namespace);
    }

}
